<script setup>
import { ref, onMounted } from 'vue';
import { useRoute, useRouter} from 'vue-router';
import { queryAdoptionByPageAPI, editAdoptionApplyAPI } from '@/apis/adopt.js';
import ButtonGroup from '@/components/ButtonGroup.vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import dayjs from 'dayjs';

const router = useRouter();
const route = useRoute();

const buttonList = [
  {
    key: 'apply',
    text: '全部申请',
    icon: {
      active: '/icon/Application-blue.png',
      normal: '/icon/Application-black.png'
    }
  },
  {
    key: 'adopted',
    text: '已通过',
    icon: {
      active: '/icon/pass-blue.png',
      normal: '/icon/pass-black.png'
    }
  },
  {
    key: 'pending',
    text: '待审核',
    icon: {
      active: '/icon/pending review-blue.png',
      normal: '/icon/pending review-black.png'
    }
  },
  {
    key: 'fail',
    text: '已拒绝',
    icon: {
      active: '/icon/fail-blue.png',
      normal: '/icon/fail-black.png'
    }
  },
];
const selectedBtn = ref('apply');

const handlerSelectBtn = (key) => {
  selectedBtn.value = key;
  currentPage.value = 1;
  queryData();
}

// 输入框
const input = ref('');

// 搜索框搜索事件
const handleSearch = () => {
  currentPage.value = 1; // 搜索时重置为第1页
  queryData(); // 触发查询
};

// 清空搜索框后自动刷新
const handleClearInput = () => {
  currentPage.value = 1;
  queryData();
};

/* ------表格------- */
const tableData = ref([]);

const handleOperate = (row) => {
  console.log(row);
}

// 状态映射样式map
const statusStyleMap = {
  'PENDING': {
    label: '待审核',
    bgColor: '#FFAD09',
  },
  'APPROVED': {
    label: '已通过',
    bgColor: '#31C84B',
  },
  'REJECTED': {
    label: '已拒绝',
    bgColor: '#E83D3D',
  }
}


/* ------分页条------- */
const total = ref(0); // 总数据条数
const currentPage = ref(1); // 当前页码
const pageSize = ref(7); // 每页显示条数

// 每页条数变化时的回调
const handleSizeChange = (val) => {
  pageSize.value = val;
  queryData();
};

// 当前页码变化时的回调
const handleCurrentChange = (val) => {
  currentPage.value = val;
  queryData();
};

const queryData = async() => {
  // 映射按钮选中状态到筛选条件
  let status = '';
  let gender = '';
  switch (selectedBtn.value) {
    case 'apply': // 全部申请
      status = '';
      break;
    case 'adopted': // 已通过
      status = 'APPROVED';
      break;
    case 'pending': // 待审核
      status = 'PENDING';
      break;
      case 'fail': // 已拒绝
      status = 'REJECTED';
      break;
  }

  // 构造请求参数
  const params = {
    page: currentPage.value,
    pageSize: pageSize.value,
    status: status, 
    gender: gender, 
    name: input.value?.trim() || '' 
  };

  try {
    // 调用 API 获取数据
    const res = await queryAdoptionByPageAPI(params);
    if (res.code === 1) {
      tableData.value = res.data.records || [];
      total.value = res.data.total || 0; // 赋值总条数，分页条才会显示正确总数
    } else {
      ElMessage.error(res.msg || '查询失败');
    }
  } catch (err) {
    ElMessage.error('网络异常，查询失败');
    console.error('查询失败：', err);
  }
};

const lookApplicationApply = (row) => {
  router.push({
    path: '/back/adopt/apply-data',
    query: {
      adoptId: row.applicationId,
      petId: row.petId
    }
  });
}

const updateApplyStatus = async (row ,isApproval) => {
  if(!isApproval) {
    // 弹出确认弹窗
    await ElMessageBox.confirm(
      '确定要拒绝这条领养申请吗？',
      '拒绝申请',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning' 
      }
    );
  }
  const status = isApproval ? 'APPROVED' : 'REJECTED';
  await editAdoptionApplyAPI({applicationId: row.applicationId, petId: row.petId, userId: row.userId, status: status});
  queryData();
}

onMounted(() => {
  queryData();
})

// 封装时间格式化函数
const formatTime = (timeStr) => {
  // 时间为空/无效时返回空字符串
  if (!timeStr) return '';
  // 格式化为 yyyy-MM-dd HH:mm:ss
  return dayjs(timeStr).format('YYYY-MM-DD HH:mm:ss');
};
</script>
<template>
        <div class="bar">
            <!-- 按钮组 -->
            <ButtonGroup
              :buttonList="buttonList"
              :selectedBtn="selectedBtn"
              @select="handlerSelectBtn"
            />
             <div class="search-input">
              <el-input
                v-model="input"
                @keyup.enter="handleSearch"
                @clear="handleClearInput"
                style="width: 452px; height: 42px;"
                placeholder="搜索宠物名称"
                clearable
              >
                <template #suffix>
                  <img src="/icon/search.png" alt="搜索图标" width="18px" height="18px" @click="handleSearch" style="cursor: pointer;">
                </template>
              </el-input>
             </div>

    </div>

    <div class="table">
            <el-table 
              :data="tableData" 
              style="width: 100%;"
              row-height="60px" 
              max-height="598px"
              :header-cell-style="{
                background: '#FAFAFA',
                color: '#404040',
                fontWeight: 'bold',
                height: '66px'
              }"
            >
            <!-- 申请人 -->
              <el-table-column prop="userName" align="center">
                <template #header>
                  <div class="table-header">
                    <img src="/icon/user-black.png" alt="" width="18px" height="18px">
                    <span>申请人</span>
                  </div>
                </template>
              </el-table-column>

              <!-- 宠物名称 -->
              <el-table-column prop="petName" align="center">
                <template #header>
                  <div class="table-header">
                    <img src="/icon/paw-sharp-black.png" alt="" width="18px" height="18px">
                    <span>宠物名称</span>
                  </div>
                </template>
              </el-table-column>

              <!-- 宠物性别 -->
              <el-table-column align="center">
                <template #header>
                  <div class="table-header">
                    <img src="/icon/gender.png" alt="" width="18px" height="18px">
                    <span>宠物性别</span>
                  </div>
                </template>
                <template #default="scope">
                  <div 
                    class="gender" 
                    :style="{ backgroundColor: scope.row.gender === 'MALE' ? '#2BAFF5' : '#F8469D' }">
                      <span>{{ scope.row.gender === 'MALE' ? '公' : '母' }}</span>
                  </div>
                </template>
              </el-table-column>
              
              <!-- 申请时间 -->
              <el-table-column align="center" width="250">
                <template #header>
                  <div class="table-header">
                    <img src="/icon/time-black.png" alt="" width="18px" height="18px">
                    <span>申请时间</span>
                  </div>
                </template>
                <template #default="scope">
                  {{ formatTime(scope.row.createdAt) }}
                </template>
              </el-table-column>
              
              <!-- 状态 -->
              <el-table-column prop="status" align="center" width="250">
                <template #header>
                  <div class="table-header">
                    <img src="/icon/status.png" alt="" width="18px" height="18px">
                    <span>状态</span>
                  </div>
                </template>
                <template #default="scope">
                  <div 
                    class="status"
                    :style="{backgroundColor: statusStyleMap[scope.row.status].bgColor}"
                  >
                    <span>{{ statusStyleMap[scope.row.status].label}}</span>
                    
                  </div>
                </template>
              </el-table-column>
              
              <!-- 操作 -->
              <el-table-column align="center">
                <template #header>
                  <div class="table-header">
                    <img src="/icon/operate.png" alt="" width="18px" height="18px">
                    <span>操作</span>
                  </div>
                </template>
                <template #default="scope">
                  <!-- 已通过状态 -->
                  <div v-if="scope.row.status === 'APPROVED'">
                    <el-button 
                      type="text" 
                      @click="lookApplicationApply(scope.row)"
                    >
                      <img 
                        src="/icon/look-1.png"
                        alt="操作" 
                        width="28px" 
                        height="28px"
                      >
                    </el-button>
                  </div>
                  <!-- 待审核状态 -->
                  <div v-else-if="scope.row.status === 'PENDING'">
                    <el-button 
                      type="text" 
                      @click="lookApplicationApply(scope.row)"
                    >
                      <img 
                        src="/icon/look-1.png"
                        alt="操作" 
                        width="28px" 
                        height="28px"
                      >
                    </el-button>
                    <el-button 
                      type="text" 
                      @click="updateApplyStatus(scope.row, true)"
                    >
                      <img 
                        src="/icon/yes.png"
                        alt="操作" 
                        width="28px" 
                        height="28px"
                      >
                    </el-button>
                    <el-button 
                      type="text" 
                      @click="updateApplyStatus(scope.row, false)"
                    >
                      <img 
                        src="/icon/no.png"
                        alt="操作" 
                        width="28px" 
                        height="28px"
                      >
                    </el-button>
                  </div>
                  <!-- 已拒绝状态 -->
                  <div v-else-if="scope.row.status === 'REJECTED'">
                    <el-button 
                      type="text" 
                      @click="lookApplicationApply(scope.row)"
                    >
                      <img 
                        src="/icon/look-1.png"
                        alt="操作" 
                        width="28px" 
                        height="28px"
                      >
                    </el-button>
                  </div>
                </template>
              </el-table-column>
            </el-table>
            <!-- 分页条 -->
             <div class="pagination">
                <el-pagination
                  v-model:current-page="currentPage"  
                  v-model:page-size="pageSize"        
                  :total="total"                     
                  layout="total, prev, pager, next, jumper, slot" 
                  @size-change="handleSizeChange"    
                  @current-change="handleCurrentChange"  
                >
                </el-pagination>
             </div>
    </div>
</template>

<style scoped>
.bar {
  display: flex;
  justify-content: space-between;
  margin-top: 12px;
  height: 60px;
}
.table-header {
  display: flex;        /* 开启 Flex 布局 */
  align-items: center;  /* 垂直居中） */
  justify-content: center; /* 水平居中 */
  gap: 6px;             /* 图标与文字的间距 */
  height: 100%;         /* 占满表头单元格的高度（66px） */
  font-size: 16px;
}
.gender {
  width: 41px;
  height: 26px;
  margin: 0 auto;
  padding: 4px 14px;
  line-height: 18px;
  color: #FFFFFF;
  border-radius: 5px;
}
.status {
  width: 59px;
  height: 26px;
  border-radius: 5px;
  color: #FFFFFF;
  font-size: 13px;
  text-align: center;
  margin: 0 auto;
  padding: 4px 10px;
  line-height: 18px;
}

/* 分页条 */
.pagination {
  position: absolute;
  right: 16px;
  margin-top: 10px;
  bottom: 20px;
}

:deep(.el-table) {
  --el-table-text-color: #2B2B2B;
  --el-table-border: none; 
}
/* 强制设置数据行（tr）的高度为72px */
:deep(.el-table .el-table__row) {
  height: 72px !important; 
}
</style>